package com.blog.util.job;

import com.blog.common.Constants;
import com.blog.config.ScheduleConstants;
import com.blog.entity.SysJob;
import com.blog.quartz.QuartzDisallowConcurrentExecution;
import com.blog.quartz.QuartzJobExecution;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.Code;
import org.quartz.*;

/**
 * @author cgx
 * @Date 2022/1/11 9:25
 * form 若依
 */
public class ScheduleUtils {


    /**
     * 检查包名是否为白名单配置
     *
     * @param invokeTarget 目标字符串
     * @return 结果
     */
    public static boolean whiteList(String invokeTarget)
    {
        String packageName = StringUtils.substringBefore(invokeTarget, ")");
        int count = StringUtils.countMatches(packageName, ".");
        if (count > 1)
        {
            if (!StringUtils.containsAnyIgnoreCase(invokeTarget, Constants.JOB_WHITELIST_STR))
            {
                return false;
            }
        }
        return true;
    }

    /**
     * 创建定时任务
     * @param scheduler
     * @param job
     * @return
     */
    public static void createScheduleJob(Scheduler scheduler, SysJob job) throws Exception {
        //判断是否允许并发执行，需要调用不同的执行类
        Class<? extends Job> jobClass = getQuartzJobClass(job);

        //构建job信息
        String jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup)).build();

        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
        scheduleBuilder = handleCronScheduleMisfirePolicy(job, scheduleBuilder);

        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(TriggerKey.triggerKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup))
                .withSchedule(scheduleBuilder.withMisfireHandlingInstructionDoNothing()).build();

        // 放入参数，运行时的方法可以获取
        jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job);

        // 判断是否存在
        if (scheduler.checkExists(getJobKey(jobId, jobGroup))) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(getJobKey(jobId, jobGroup));
        }


        scheduler.scheduleJob(jobDetail, trigger);

        // 暂停任务
        if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
    }

    /**
     * 构建任务键对象
     */
    public static JobKey getJobKey(String jobId, String jobGroup)
    {
        return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup);
    }


    /**
     * 设置定时任务策略
     */
    public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb) throws Exception
    {
        switch (job.getMisfirePolicy())
        {
            case ScheduleConstants.MISFIRE_DEFAULT:
                return cb;
            case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
                return cb.withMisfireHandlingInstructionIgnoreMisfires();
            case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
                return cb.withMisfireHandlingInstructionFireAndProceed();
            case ScheduleConstants.MISFIRE_DO_NOTHING:
                return cb.withMisfireHandlingInstructionDoNothing();
            default:
                throw new Exception("The task misfire policy '" + job.getMisfirePolicy()
                        + "' cannot be used in cron schedule tasks");
        }
    }



    public static Class<? extends Job> getQuartzJobClass(SysJob job){

        boolean isConcurrent = "0".equals(job.getConcurrent());
        return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class;
    }
}
